﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Services;
using Autorent.DAL;

namespace Autorent.Service
{
    /// <summary>
    /// Class adds security functionality to DataService. It assures that current user has specific role.
    /// </summary>
    public class SecureAutoRentDataService : DataService<AutoRentEntities>
    {
        /// <summary>
        /// You can stop any restrictions setting this to true.
        /// </summary>
        protected virtual bool AllowAnonymousAccess { get { return false; }}
        protected virtual string SystemUserRole { get { return ""; } }

        protected override void OnStartProcessingRequest(ProcessRequestArgs args)
        {
            if (AllowAnonymousAccess)
                return;
            string name = args.OperationContext.RequestHeaders["AuthorizationName"];
            string pass = args.OperationContext.RequestHeaders["AuthorizationPass"];

            AutoRentEntities ctx = new AutoRentEntities();
            var result = from users in ctx.SystemUsers
                         where users.SystemUserName == name && users.SystemUserPassword == pass
                         select users;

            List<SystemUser> sysUsers = result.ToList();
            if (sysUsers.Count != 1)
                throw new DataServiceException(401, "401 - Unauthorized");
            if (sysUsers.First().SystemUserRole != SystemUserRole)
                throw new DataServiceException(404, "404 Forbidden");
            
            //try
            //{
            //}
            //catch (Exception e)
            //{
            //    using (StreamWriter sw = new StreamWriter("F:\\error.txt"))
            //    {
            //        sw.Write(e);
            //    }
            //}
        }
    }
}